package com.tenbent.product.base.action;

import java.util.Date;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.tenbent.product.base.Message.Message;
import com.tenbent.product.base.dto.BaseDto;
import com.tenbent.product.base.dto.change.ChangeBoToDto;
import com.tenbent.product.base.exception.TenbentApiBadRequestException;
import com.tenbent.product.base.utils.DateUtil;
import com.tenbent.product.base.utils.SpringContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;

/**
 * 控制器基类
 * 
 * @author Randy Yan
 * 
 */
public class BaseController {

	protected Logger logger = null;

	public BaseController() {

		logger = LoggerFactory.getLogger(getClass());
	}

	@Autowired
	protected MessageSource messageSource;

	@Autowired
	@Qualifier("changeBoToDto")
	protected ChangeBoToDto change;

	public ResponseEntity<Message> responseEntity(Integer statusCode, String statusMsg, Object obj) {
		return new ResponseEntity<>(new Message(statusCode, statusMsg, obj), HttpStatus.OK);
	}

	/**
	 * 处理验证错误验证
	 */
	public void processErrors(Errors errors) {
		if (errors.hasErrors()) {
			throw new TenbentApiBadRequestException(errors.getFieldError().getDefaultMessage());
		}
	}

	/**
	 * 设置新增操作人
	 */
	public void settingSaveManager(BaseDto baseDto, Integer managerId) {
		baseDto.setCreateId(managerId);
		baseDto.setModifyId(managerId);
	}

	/**
	 * 设置修改操作人
	 */
	public void settingModiferManager(BaseDto baseDto, Integer managerId) {
		baseDto.setModifyId(managerId);
	}

	/**
	 * 获取本地locale
	 */
	public Locale getLocale() {

		// 通过设置客户端 Accept-Language cn-zh,cn;q=0.5 或 en-us,en;q=0.5
		return LocaleContextHolder.getLocale();
	}

	/**
	 * 获取message
	 */
	public String getMessage(String key, Object[] args) {
		return messageSource.getMessage(key, args, LocaleContextHolder.getLocale());
	}

	/**
	 *
	 * 得到参数
	 */
	public String getParameter(String key) {

		return (String) SpringContextUtil.getReqParameter(key);
	}

	/**
	 * 获取session
	 * 
	 */
	public HttpSession getSession(HttpServletRequest req) {

		return req.getSession();
	}

	/**
	 * 得到服务器日期
	 * 
	 * @return
	 */
	public String getServerDate() {
		Date now = new Date();
		return DateUtil.dateFormat(now, DateUtil.PATTERN_LONG);
	}

}
